package com.meituan.catering.management.shop.dao.converter;

import com.meituan.catering.management.shop.biz.model.request.SearchShopBizRequest;
import com.meituan.catering.management.shop.dao.model.request.SearchShopDataRequest;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Believe
 * Date 2022/5/19 14:43
 */
public class PageDOConverter {
    private static final String FUZZY_MATCH_PATTERN = "%{0}%";

    public static SearchShopDataRequest toPageDO(SearchShopBizRequest request) {
        if (request == null) {
            return null;
        }
        SearchShopDataRequest pageDO = new SearchShopDataRequest();
        pageDO.setPageIndex(request.getPageIndex() - 1);
        pageDO.setPageSize(request.getPageSize());
        pageDO.setEnabled(request.getEnabled());
        pageDO.setBusinessType(request.getBusinessType());
        pageDO.setManagementType(request.getManagementType());
        pageDO.setKeyword(MessageFormat.format(FUZZY_MATCH_PATTERN, request.getKeyword()));
        pageDO.setSortFields(toDataDOSort(request.getSortFields()));
        return pageDO;
    }

    public static List<SearchShopDataRequest.SortField> toDataDOSort(List<SearchShopBizRequest.SortField> sortFields) {
        if (!sortFields.isEmpty()) {
            return null;
        }
        List<SearchShopDataRequest.SortField> sortFieldList = new ArrayList<>();
        SearchShopDataRequest.SortField enabledField = new SearchShopDataRequest.SortField("enabled", "desc");
        SearchShopDataRequest.SortField lastModifyField = new SearchShopDataRequest.SortField("last_modified_at", "desc");
        if (sortFields.isEmpty()) {
            sortFieldList.add(enabledField);
            sortFieldList.add(lastModifyField);
            return sortFieldList;
        }
        for (SearchShopBizRequest.SortField sortField : sortFields) {
            SearchShopDataRequest.SortField field = new SearchShopDataRequest.SortField();
            field.setField(sortField.getField());
            field.setAsc(sortField.getAsc());
            sortFieldList.add(field);
        }
        return sortFieldList;
    }

}
